package com.gitee.booting.dspi;

import com.gitee.booting.balancer4j.QueueLoadBalancer;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicReference;

public class Extensions {
    /**
     * echo dspi | md5sum
     */
    public static final String ENDPOINT = "/b1055fa857cef9835fda47fac9247261";
    public static final String COMMA = ",";
    public static final String MINUS = "-";
    public static final String SLASH = "/";
    public static final String EMPTY = "";
    public static final String SERVICE_DEFAULT = EMPTY;
    public static final String SERVICE_NAME_SEPARATOR = "=";
    public static final String PROVIDER = "dspi-provider";

    private static final AtomicReference<RestTemplate> REST_TEMPLATE = new AtomicReference<>();
    private static final AtomicReference<DiscoveryClient> DISCOVERY_CLIENT = new AtomicReference<>();
    private static final AtomicReference<QueueLoadBalancer> LOAD_BALANCER = new AtomicReference<>();

    public Extensions init(RestTemplate template, DiscoveryClient client, QueueLoadBalancer balancer) {
        REST_TEMPLATE.set(template);
        DISCOVERY_CLIENT.set(client);
        LOAD_BALANCER.set(balancer);
        return this;
    }

    public static <T> T get(Class<T> type, String service) {
        return get(type, service, SERVICE_DEFAULT);
    }

    public static <T> T get(Class<T> type, String service, String name) {
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type},
            new Extension(REST_TEMPLATE.get(), DISCOVERY_CLIENT.get(), LOAD_BALANCER.get(),
                type, service, SERVICE_DEFAULT.equals(name) ? SERVICE_DEFAULT : name));
    }
}
